#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFile>
#include <QFileDialog>
#include <QDebug>
#include <QMessageBox>
#include <QTextCodec>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),plotStatus(false),targetStatus(false),
    ui(new Ui::MainWindow)
{
    QTextCodec::setCodecForLocale(QTextCodec::codecForName("GB18030"));
    ui->setupUi(this);
    setupMain();
    connect(ui->pushButtonOpen,SIGNAL(clicked(bool)),this,SLOT(OpenConfig()));
    connect(ui->pushButtonSave,SIGNAL(clicked(bool)),this,SLOT(SaveConfig()));
    connect(ui->pushButtonSend,SIGNAL(clicked(bool)),this,SLOT(SendData()));
    connect(ui->pushButtonPlot,SIGNAL(clicked(bool)),this,SLOT(PlotData()));
    connect(ui->pushButtonTarget,SIGNAL(clicked(bool)),this,SLOT(PlotTarget()));
    connect(ui->widgetCom,SIGNAL(ReadyRecv(QByteArray&)),this,SLOT(RecvData(QByteArray&)));
}

MainWindow::~MainWindow()
{
    delete ui;
    delete gridLayoutPara;
    delete []lineEditPara;
    delete []labelPara;
    delete gridLayoutLed;
    delete []ledLed;
    delete []labelLed;
    delete gridLayoutData;
    delete []lineEditData;
    delete []labelData;
}

void MainWindow::closeEvent(QCloseEvent *event){
    if(plotStatus){
        plot->close();
        delete plot;
    }
    if(targetStatus){
        target->close();
        delete target;
    }
}

void MainWindow::setupMain(){
    QFile file("config.ini");
    if(!file.exists()){
        QMessageBox::warning(this,tr("error"),tr("no file(config.ini)"),tr("ok"));
        exit(1);
    }
    iniFile = new minIni("config.ini");
    int i=0,j=0;
    string section,key;
    while((section=iniFile->getsection(i++))!=""){
        j=0;
        if(section=="led")
            while((key=iniFile->getkey(section,j++))!="")
                ledName.push_back(QString::fromStdString(key));
        else if(section=="para")
            while((key=iniFile->getkey(section,j++))!="")
                paraName.push_back(QString::fromStdString(key));
        else if(section=="data")
            while((key=iniFile->getkey(section,j++))!="")
                dataName.push_back(QString::fromStdString(key));
    }
    int lineNum = 3;
    if(ledName.size()){
        gridLayoutLed = new QGridLayout(ui->widgetLed);
        ledLed = new QLed[ledName.size()];
        labelLed = new QLabel[ledName.size()];
        ledValue.resize(ledName.size());
    }
    for(i=0;i<ledName.size();i++){
        gridLayoutLed->addWidget(&labelLed[i],i/lineNum,i%lineNum*2,1,1);
        gridLayoutLed->addWidget(&ledLed[i],i/lineNum,i%lineNum*2+1,1,1);
        labelLed[i].setText(ledName[i]);
    }
    if(paraName.size()){
        gridLayoutPara = new QGridLayout(ui->widgetPara);
        labelPara = new QLabel[paraName.size()];
        lineEditPara = new QLineEdit[paraName.size()];
        paraValue.resize(paraName.size());
    }
    for(i=0;i<paraName.size();i++){
        paraValue[i]=iniFile->getd("para",paraName[i].toStdString());
        gridLayoutPara->addWidget(&labelPara[i],i/lineNum,i%lineNum*2,1,1);
        gridLayoutPara->addWidget(&lineEditPara[i],i/lineNum,i%lineNum*2+1,1,1);
        labelPara[i].setText(paraName[i]);
        lineEditPara[i].setText(QString::number(paraValue[i]));
    }
    if(dataName.size()){
        gridLayoutData = new QGridLayout(ui->widgetData);
        labelData = new QLabel[dataName.size()];
        lineEditData = new QLineEdit[dataName.size()];
        dataValue.resize(dataName.size());
    }
    for(i=0;i<dataName.size();i++){
        dataValue[i]=iniFile->getd("data",dataName[i].toStdString());
        gridLayoutData->addWidget(&labelData[i],i/lineNum,i%lineNum*2,1,1);
        gridLayoutData->addWidget(&lineEditData[i],i/lineNum,i%lineNum*2+1,1,1);
        labelData[i].setText(dataName[i]);
        lineEditData[i].setText(QString::number(dataValue[i]));
    }
}

void MainWindow::OpenConfig(){
    QString fileName = QFileDialog::getOpenFileName(this, tr("Read File"));
    if(fileName.size()){
        QFile f(fileName);
        if(f.exists()){
            minIni cfgfile(fileName.toStdString());
            for(int i=0;i<paraName.size();i++){
                paraValue[i]=cfgfile.getd("para",paraName[i].toStdString());
                lineEditPara[i].setText(QString::number(paraValue[i]));
            }
            return;
        }
    }
    QMessageBox::information(this,"error","could not open file!","ok");
}

void MainWindow::SaveConfig(){
    for(int i=0;i<paraName.size();i++){
        paraValue[i] = lineEditPara[i].text().toDouble();
        iniFile->put("para",paraName[i].toStdString(),lineEditPara[i].text().toStdString());
    }
    QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"));
    if(fileName.size()){
        QFile f(fileName);
        if(f.exists())f.remove();
        if(QFile::copy("config.ini", fileName))
            QMessageBox::information(this,"tip","save file success!","ok");
    }
}

void MainWindow::SendData(){
    QString str = "$PCM,123,45,6563\r\n";
    QByteArray data = str.toLatin1();
    SendData(data);
}

void MainWindow::SendData(QByteArray &data){
    if(ui->widgetCom->getStatus()){
        ui->widgetCom->SendPackets(data);
    }
    else
        QMessageBox::information(this,"warning","try to connect!","ok");
}

void MainWindow::SendTarget(QVector<pair<double,double>> &v){
    if(v.size()==0)return;
    QString str="$TRG,";
    for(int i=0;i<v.size();i++){
        str += QString("%1,%2;") .arg(v[i].first) .arg(v[i].second);
    }
    QByteArray data = str.toLatin1();
    SendData(data);
}

void MainWindow::RecvData(QByteArray &data){
    QVector<double> v;
    QString str = data;
    static double index = 0;
    v.push_back(index++);
    QStringList list= str.split(',');
    if(list.at(0)=="$PCM"){
        for(int i=1;i<list.size();i++){
            double data = list.at(i).toDouble();
            v.push_back(data);
        }
        emit sendtoPlot(v);
    }
    else if(list.at(0)=="$TRG"){
        double data1=list.at(1).toDouble();
        double data2=list.at(2).toDouble();
        emit sendtoTraget(data1,data2);
    }
}

void MainWindow::PlotData(){
    if(!plotStatus){
        plotStatus = true;
        plot = new Plot;
        plot->setAttribute(Qt::WA_DeleteOnClose);
        connect(plot,SIGNAL(destroyed(QObject*)),this,SLOT(PlotDataClose()));
        connect(this,SIGNAL(sendtoPlot(QVector<double>&)),plot,SLOT(realtimeDataSlot(QVector<double>&)));
        plot->show();
    }
    else{
        plotStatus = false;
        plot->close();
        delete plot;
    }
}

void MainWindow::PlotTarget(){
    if(!targetStatus){
        targetStatus = true;
        target = new trajectory;
        target->setAttribute(Qt::WA_DeleteOnClose);
        connect(target,SIGNAL(destroyed(QObject*)),this,SLOT(PlotTargetClose()));
        connect(target,SIGNAL(sendData(QVector<pair<double,double> >&)),this,SLOT(SendTarget(QVector<pair<double,double> >&)));
        connect(this,SIGNAL(sendtoTraget(double,double)),target,SLOT(RecvPoint(double,double)));
        target->show();
    }
    else{
        targetStatus = false;
        target->close();
        delete target;
    }
}

void MainWindow::PlotDataClose(){
    plotStatus = false;
}

void MainWindow::PlotTargetClose(){
    targetStatus = false;
}

